package org.timemanager.view;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * this activity gives user the chance to insert a new record 
 * when a record is forgotten to add into the database,
 * update or delete one finished event such as its start time,end time,or even the event itself
 */
public class RecordActivity extends Activity {
	/**
	 * action to add a new record.
	 */
	public static final String ACTION_ADD="org.timemanager.action.record_add";
	/**
	 * action to update a existed record.
	 */
	public static final String ACTION_UPDATE="org.timemanager.action.record_update";
	
	/**
	 * action add:0,action update:1
	 */
	private int operateType;
	private DatabaseTool databaseTool;
	/**
	 * store the record id and its all properties when updating the record.
	 */
	private int recordId;
	
	private TextView recordTitle;
	private EditText recordStartTime;
	private EditText recordEndTime;
	private EditText recordStartDate;
	private EditText recordEndDate;
	private MyAutoCompleteTextView recordEvent;
	private Button recordSave;
	private Button recordCancel;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.record_view);
		initAllConfiguration();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try{
			databaseTool.close();
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
	/**
	 * initialize all global parameters.
	 */
	private void initAllConfiguration(){
		databaseTool=new DatabaseTool(RecordActivity.this);
		
		String action=getIntent().getAction();
		if(action.equals(ACTION_ADD)){
			operateType=0;
		}else if(action.equals(ACTION_UPDATE)){
			operateType=1;
			recordId=getIntent().getIntExtra("recordId", -1);
		}
		
		recordTitle=(TextView) findViewById(R.id.record_view_title);
		recordEvent=(MyAutoCompleteTextView) findViewById(R.id.record_view_event);
		setEventAdapter();
		recordStartTime=(EditText) findViewById(R.id.record_view_start_time);
		recordEndTime=(EditText) findViewById(R.id.record_view_end_time);
		recordStartDate=(EditText) findViewById(R.id.record_view_start_date);
		recordEndDate=(EditText) findViewById(R.id.record_view_end_date);		
		
		recordSave=(Button) findViewById(R.id.record_view_save);
		recordCancel=(Button) findViewById(R.id.record_view_cancel);
		
		recordStartTime.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				recordTitle.requestFocus();
				showDialog(R.id.record_view_start_time);
			}
		});
		recordStartDate.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				recordTitle.requestFocus();
				showDialog(R.id.record_view_start_date);
			}
		});
		recordEndTime.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				recordTitle.requestFocus();
				showDialog(R.id.record_view_end_time);
			}
		});
		recordEndDate.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				recordTitle.requestFocus();
				showDialog(R.id.record_view_end_date);
			}
		});
		recordCancel.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				finish();
			}
		});
		if(operateType==0){
			recordTitle.setText(R.string.record_view_add);
			recordSave.setText(R.string.record_view_save);
		}
		else if(operateType==1){
			recordTitle.setText(R.string.record_view_update);
			recordSave.setText(R.string.record_update);
			
			Cursor cursor=databaseTool.getRecord(recordId);
			cursor.moveToFirst();
			recordEvent.setText(cursor.getString(2));
			String startDateString=cursor.getString(3);
			String endDateString=cursor.getString(4);
			recordStartDate.setText(startDateString.substring(0, 10));
			recordStartTime.setText(startDateString.substring(11));
			recordEndDate.setText(endDateString.substring(0, 10));
			recordEndTime.setText(endDateString.substring(11));
//			try{
//				cursor.close();
//			}catch (Exception e) {
//				// TODO: handle exception
//			}
		}
		
		recordSave.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				String recordEventString=recordEvent.getText().toString();
				recordEventString=recordEventString.trim();
				if(recordEventString=="" || recordEventString.length()==0){
					Toast.makeText(RecordActivity.this, getText(
							R.string.record_view_event_name_no), Toast.LENGTH_SHORT).show();
					return;
				}
				String recordStartDateString=recordStartDate.getText().toString();
				recordStartDateString=recordStartDateString.trim();
				if(recordStartDateString=="" || recordStartDateString.length()==0){
					Toast.makeText(RecordActivity.this, getText(
							R.string.record_view_start_date_no), Toast.LENGTH_SHORT).show();
					return;
				}
				String recordStartTimeString=recordStartTime.getText().toString();
				recordStartTimeString=recordStartTimeString.trim();
				if(recordStartTimeString=="" || recordStartTimeString.length()==0){
					Toast.makeText(RecordActivity.this, getText(
							R.string.record_view_start_time_no), Toast.LENGTH_SHORT).show();
					return;
				}
				String recordEndDateString=recordEndDate.getText().toString();
				recordEndDateString=recordEndDateString.trim();
				if(recordEndDateString=="" || recordEndDateString.length()==0){
					Toast.makeText(RecordActivity.this, getText(
							R.string.record_view_end_date_no), Toast.LENGTH_SHORT).show();
					return;
				}
				String recordEndTimeString=recordEndTime.getText().toString();
				recordEndTimeString=recordEndTimeString.trim();
				if(recordEndTimeString=="" || recordEndTimeString.length()==0){
					Toast.makeText(RecordActivity.this, getText(
							R.string.record_view_end_time_no), Toast.LENGTH_SHORT).show();
					return;
				}
				Calendar startCalendar=Calendar.getInstance();
				startCalendar.setTime(DailyRecordActivity.curCalendar.getTime());
				startCalendar.set(Calendar.YEAR,
						Integer.parseInt(recordStartDateString.substring(0, 4)));
				startCalendar.set(Calendar.MONTH,
						Integer.parseInt(recordStartDateString.substring(5, 7))-1);
				startCalendar.set(Calendar.DAY_OF_MONTH,
						Integer.parseInt(recordStartDateString.substring(8)));
				startCalendar.set(Calendar.HOUR_OF_DAY, 
						Integer.parseInt(recordStartTimeString.substring(0, 2)));
				startCalendar.set(Calendar.MINUTE, 
						Integer.parseInt(recordStartTimeString.substring(3)));
//				Log.e("startCalendar",startCalendar.getTime().toString());
//				Toast.makeText(RecordActivity.this, 
//						startCalendar.getTime().toString(), 5000).show();
				
				Calendar endCalendar=Calendar.getInstance();
				endCalendar.setTime(DailyRecordActivity.curCalendar.getTime());
				endCalendar.set(Calendar.YEAR,
						Integer.parseInt(recordEndDateString.substring(0, 4)));
				endCalendar.set(Calendar.MONTH,
						Integer.parseInt(recordEndDateString.substring(5, 7))-1);
				endCalendar.set(Calendar.DAY_OF_MONTH,
						Integer.parseInt(recordEndDateString.substring(8)));
				endCalendar.set(Calendar.HOUR_OF_DAY, 
						Integer.parseInt(recordEndTimeString.substring(0, 2)));
				endCalendar.set(Calendar.MINUTE, 
						Integer.parseInt(recordEndTimeString.substring(3)));
				
//				Log.e("endCalendar",endCalendar.getTime().toString());
//				Toast.makeText(RecordActivity.this, 
//						endCalendar.getTime().toString(), 5000).show();			
				/*
				 * when end time is before or equal to start time
				 * then it means it is the next day
				 */
				Log.e("start time",startCalendar.getTime().toString());
				Log.e("end time",endCalendar.getTime().toString());
				if(startCalendar.after(endCalendar)){
					Log.e("start > end","error");
					Toast.makeText(RecordActivity.this, getText(
							R.string.record_view_start_over_end), Toast.LENGTH_SHORT).show();
					return;
				}
				/*
				 * end time can not be over now
				 */
				Log.e("current",Calendar.getInstance().getTime().toString());
				if(endCalendar.after(Calendar.getInstance())){
					Toast.makeText(RecordActivity.this, getText(
							R.string.record_view_time_limit), Toast.LENGTH_SHORT).show();
					return;
				}
				if(operateType==0){
					
					/*
					 * end time must before last event (current doing)
					 * it can suggest customer to finish last event first
					 */
					if(databaseTool.checkRecordOverLast(endCalendar.getTime())){
						Toast.makeText(RecordActivity.this, getText(
								R.string.record_view_time_over_last), Toast.LENGTH_SHORT).show();
						return;
					}
					int checkResult=databaseTool.checkEventName(recordEventString);
					if(checkResult==-1){
						/*
						 * when the event is not matched 
						 * then it means a new event is added
						 */
						Log.e("new event",recordEventString+" "+checkResult);
						checkResult=(int) databaseTool.insertEvent(recordEventString, -1, -1, "");
						TimeManagerWidget.clearItems();
						setEventAdapter();
					}
					
					if(!databaseTool.addRecord(checkResult, 
							startCalendar.getTime(), endCalendar.getTime())){
						Toast.makeText(RecordActivity.this, getText(
								R.string.record_view_add_cross_event), Toast.LENGTH_SHORT).show();
						return;
					}
					Toast.makeText(RecordActivity.this, getText(
							R.string.record_view_add_success), Toast.LENGTH_SHORT).show();
				}
				else if(operateType==1){

					/*
					 * end time must before last event (current doing)
					 * it can suggest customer to finish last event first
					 */
					if(databaseTool.checkRecordBeforePrevious(recordId, startCalendar.getTime())){
						Toast.makeText(RecordActivity.this, getText(
								R.string.record_view_time_before_previous), Toast.LENGTH_SHORT).show();
						return;
					}
					if(databaseTool.checkRecordAfterLast(recordId, endCalendar.getTime())){
						Toast.makeText(RecordActivity.this, getText(
								R.string.record_view_time_after_last), Toast.LENGTH_SHORT).show();
						return;
					}
					int checkResult=databaseTool.checkEventName(recordEventString);
					if(checkResult==-1){
						/*
						 * when the event is not matched 
						 * then it means a new event is added
						 */
						Log.e("new event",recordEventString+" "+checkResult);
						checkResult=(int) databaseTool.insertEvent(recordEventString, -1, -1, "");
						TimeManagerWidget.clearItems();
						/*
						 * now there is no need to update event drop down list adapter
						 * since it is OK to update
						 */
						//setEventAdapter();
					}
					
					/*
					 * there is no way to update or delete current doing event
					 */
					databaseTool.updateRecord(recordId,checkResult, 
								startCalendar.getTime(), endCalendar.getTime());
					Toast.makeText(RecordActivity.this, getText(
							R.string.record_view_update_success), Toast.LENGTH_SHORT).show();
						
				}
				Intent intent=new Intent();
				setResult(RESULT_OK, intent);
				finish();
			}
		});
	}

	@Override
	protected Dialog onCreateDialog(final int id) {
		Calendar calendar=Calendar.getInstance();
		AlertDialog dialog=null;
		if(operateType==0){
			if(id==R.id.record_view_start_time){
				dialog=new TimePickerDialog(RecordActivity.this, new OnTimeSetListener() {
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						recordStartTime.setText(String.format("%02d:%02d", hourOfDay,minute));
					}
				}, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
				dialog.setTitle(R.string.set_record_view_start_time);
			}
			else if(id==R.id.record_view_end_time){
				dialog=new TimePickerDialog(RecordActivity.this, new OnTimeSetListener() {
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
							recordEndTime.setText(String.format("%02d:%02d", hourOfDay,minute));
					}
				}, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
				dialog.setTitle(R.string.set_record_view_end_time);
			}
			else if(id==R.id.record_view_start_date){
				dialog = new DatePickerDialog(RecordActivity.this,new OnDateSetListener() {
					
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						recordStartDate.setText(String.format("%04d-%02d-%02d", 
								year,monthOfYear+1,dayOfMonth));
					}
				},calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),
	    				calendar.get(Calendar.DAY_OF_MONTH));
				dialog.setTitle(R.string.set_record_view_start_date);
			}
			else if(id==R.id.record_view_end_date){
				dialog = new DatePickerDialog(RecordActivity.this,new OnDateSetListener() {
					
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						recordEndDate.setText(String.format("%04d-%02d-%02d", 
								year,monthOfYear+1,dayOfMonth));
					}
				},calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),
	    				calendar.get(Calendar.DAY_OF_MONTH));
				dialog.setTitle(R.string.set_record_view_end_date);
			}
		}
		else if(operateType==1){
			Cursor cursor=databaseTool.getRecord(recordId);
			cursor.moveToFirst();
			
			if(id==R.id.record_view_start_time){
				String startTimeString=cursor.getString(3).substring(11);
				dialog=new TimePickerDialog(RecordActivity.this, new OnTimeSetListener() {
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
							recordStartTime.setText(String.format("%02d:%02d", hourOfDay,minute));
						
					}
				}, Integer.parseInt(startTimeString.substring(0,2)), 
					Integer.parseInt(startTimeString.substring(3)), true);
				dialog.setTitle(R.string.set_record_view_start_time);
			}
			else if(id==R.id.record_view_end_time){
				String endTimeString=cursor.getString(4).substring(11);
				dialog=new TimePickerDialog(RecordActivity.this, new OnTimeSetListener() {
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
							recordEndTime.setText(String.format("%02d:%02d", hourOfDay,minute));
					}
				}, Integer.parseInt(endTimeString.substring(0,2)), 
					Integer.parseInt(endTimeString.substring(3)), true);
				dialog.setTitle(R.string.set_record_view_end_time);
			}
			else if(id==R.id.record_view_start_date){
				String startTimeString=cursor.getString(3);
				dialog = new DatePickerDialog(RecordActivity.this,new OnDateSetListener() {
					
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						recordStartDate.setText(String.format("%04d-%02d-%02d", 
								year,monthOfYear+1,dayOfMonth));
					}
				},Integer.parseInt(startTimeString.substring(0,4)),
					Integer.parseInt(startTimeString.substring(5,7))-1,
					Integer.parseInt(startTimeString.substring(8,10)));
				dialog.setTitle(R.string.set_record_view_start_date);
			}
			else if(id==R.id.record_view_end_date){
				String endTimeString=cursor.getString(4);
				dialog = new DatePickerDialog(RecordActivity.this,new OnDateSetListener() {
					
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						recordEndDate.setText(String.format("%04d-%02d-%02d", 
								year,monthOfYear+1,dayOfMonth));
					}
				},Integer.parseInt(endTimeString.substring(0,4)),
					Integer.parseInt(endTimeString.substring(5,7))-1,
					Integer.parseInt(endTimeString.substring(8,10)));
				dialog.setTitle(R.string.set_record_view_end_date);
			}
//			try{
//				cursor.close();
//			}catch (Exception e) {
//				// TODO: handle exception
//			}
		}

		return dialog;
	}
	/**
	 * provide the event data source for the auto complete text view.
	 */
	private void setEventAdapter(){
		ArrayList<String> eventNameList=new ArrayList<String>();
		Cursor allEvent=databaseTool.getAllEvents();
		while(allEvent.moveToNext()){
			eventNameList.add(allEvent.getString(1));
		}
//		try{
//			allEvent.close();
//		}catch (Exception e) {
//			// TODO: handle exception
//		}
		recordEvent.setAdapter(new ArrayAdapter<String>(RecordActivity.this, 
				android.R.layout.simple_dropdown_item_1line,
				(String[]) eventNameList.toArray(new String[eventNameList.size()])));
	}
}
